package com.example.springboot.config.responseadvice;

import com.example.springboot.bean.Result;
import com.example.springboot.config.anotation.ignorerestfulapi.IgnoreRestFulApi;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author chenzhangkun
 * @ClassName CommonResultResponseAdvice
 * @description: TODO
 * @date 2024年10月29日
 */
@ControllerAdvice
public class CommonResultResponseAdvice implements ResponseBodyAdvice<Object> {
	@Override
	public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
		return methodParameter.hasMethodAnnotation(IgnoreRestFulApi.class) && !methodParameter.getParameterType().isAssignableFrom(Result.class);
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
		if (methodParameter.getParameterType().isAssignableFrom(Void.class)){
			return new Result<Void>();
		}
		if (!(body instanceof Result)){
			return new Result<>(body);
		}
       // todo 其他处理
		return null;
	}
}
